package main

import (
	"flag"
	"fmt"
	"net"
	"syscall"
)

const maxRead = 25

func main() {
	// 解析输入获取host和port
	// 开启监听
	// 处理消息
	flag.Parse()
	if flag.NArg() != 2 {
		fmt.Println("输入地址和端口: host port")
		return
	}
	listener := initListener(flag.Arg(0) + ":" + flag.Arg(1))

	for {
		conn, err := listener.Accept()
		checkErr(err, "Accept")
		go connectHandler(conn)
	}
}

func initListener(remote string) *net.TCPListener {
	serrverAddr, err := net.ResolveTCPAddr("tcp", remote)
	checkErr(err, "Resolving address:port failed: '"+remote+"'")
	listener, err := net.ListenTCP("tcp", serrverAddr)
	checkErr(err, "ListenTCP")
	fmt.Println("Listen from:", listener.Addr().String())

	return listener
}

func connectHandler(conn net.Conn) {
	// print connectFrom
	connFrom := conn.RemoteAddr().String()
	fmt.Println("Connect From:", connFrom)
	// send hellot to connect client
	sayHelloToClient(conn)
	for {
		ibuf := make([]byte, maxRead+1)
		len, err := conn.Read(ibuf[0:maxRead])
		ibuf[maxRead] = 0
		switch err {
		case nil:
			handleMsg(len, err, ibuf)
		case syscall.EAGAIN:
			continue
		default:
			goto DISCONNECT
		}
	}
DISCONNECT:
	err := conn.Close()
	fmt.Println("Close Connection:", connFrom)
	checkErr(err, "Close")

}

func handleMsg(len int, err error, buff []byte) {
	if len > 0 {
		fmt.Print("<", len, ":")
		for i := 0; ; i++ {
			if buff[i] == 0 {
				break
			}
			fmt.Printf("%c", buff[i])
		}
		fmt.Println(">")
	}
}

func sayHelloToClient(conn net.Conn) {
	wrote, err := conn.Write([]byte("Welcome login server"))
	checkErr(err, fmt.Sprintf("Write: Wrote %d bytes", wrote))
}

func checkErr(err error, info string) {
	if err != nil {
		panic("Error " + info + ": " + err.Error())
	}
}
